package com.vclee.fast.integration.imserver;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vclee.fast.utils.exception.Assert;
import com.vclee.fast.utils.model.Bson;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;


public class PushUtils {

    private static final Map<String, Channel> channelMap = new ConcurrentHashMap<>();
    private final static Logger logger = LoggerFactory.getLogger(PushUtils.class);

    private final static List<String> plateList = Arrays.asList("WEB", "APP", "WAP","WMP");


    public static String getPlatform(String platform) {
        Assert.claim(!plateList.contains(platform), "IM参数不合法");
        return platform;
    }

    public static boolean getImStatus(String pushId){
        return channelMap.get(pushId)!=null;
    }

    public static void tryPush(Long userId, ImNotice notice) {
        plateList.forEach(platform-> tryPush( platform+userId,notice));
    }

    /**
     *
     * @param pushId 接收设备号cid
     * @param notice 发送给接收方的前端数据
     */
    private static void tryPush(String pushId, ImNotice notice) {
        if(!Assert.isBlank(pushId)){
            Channel channel = channelMap.get(pushId);
            if (channel != null) {
                String payload = Bson.toString(notice);
                logger.info("===>im推送:{},通道:{},消息体:{}",pushId,channel.id().asShortText(),payload);
                PingWebSocketFrame ping = new PingWebSocketFrame();
                channel.writeAndFlush(ping);
                TextWebSocketFrame tws = new TextWebSocketFrame(payload);
                channel.writeAndFlush(tws);
            }
        }
    }

    /**
     * 用户上线
     *
     * @param pushId 设备Id
     * @param channel 当前通道
     *
     */
    static void forceOnline(String pushId, Channel channel) {
        String key = channel.id().asShortText();
        Channel oldChannel = channelMap.put(pushId, channel);
        if (oldChannel != null) {
            oldChannel.disconnect();
            logger.info("===> IM重复连接:{},新的channel:{},旧的channel:{}", pushId,key,oldChannel.id().asShortText());
        }else{
            logger.info("===> IM用户上线:{},channel通道为:{}", pushId,key);
        }
    }

   public static void forceOffline(String pushId) {
        channelMap.keySet().removeIf(key -> key.equals(pushId));
    }

    /**
     * 下线
     */
    static void forceOffline(Channel channel) {
        String key = channel.id().asShortText();
        logger.info("channel断连:{}",key);
        channelMap.values().removeIf(value -> value.equals(channel));
    }

    private static String replaceBlank(String str) {
        return Pattern.compile("\\s*|\t|\r|\n").matcher(str).replaceAll("");
    }

}
